﻿namespace Pub.Class
{
    using System;
    using System.Runtime.InteropServices;

    public class SerializeHelper : Disposable
    {
        private ISerialize serialize;
        private SerializeEnum serializeEnum;

        public SerializeHelper(SerializeEnum serializeEnum)
        {
            this.serializeEnum = serializeEnum;
            this.init();
        }

        public SerializeHelper(string serializeEnum)
        {
            this.serializeEnum = serializeEnum.ToEnum<SerializeEnum>();
            this.init();
        }

        public T DecodeDeserialize<T>(string data, string key = "")
        {
            return this.serialize.DecodeDeserialize<T>(data, key);
        }

        public T Deserialize<T>(string data)
        {
            return this.serialize.Deserialize<T>(data);
        }

        public T DeserializeFile<T>(string fileName)
        {
            return this.serialize.DeserializeFile<T>(fileName);
        }

        private void init()
        {
            switch (this.serializeEnum)
            {
                case SerializeEnum.xml:
                    this.serialize = new XmlSerialize();
                    return;

                case SerializeEnum.json:
                    this.serialize = new JsonSerialize();
                    return;

                case SerializeEnum.binary:
                    this.serialize = new BinarySerialize();
                    return;
            }
            this.serialize = new JsonSerialize();
        }

        protected override void InternalDispose()
        {
            this.serialize = null;
            base.InternalDispose();
        }

        public string Serialize(object o)
        {
            return this.serialize.Serialize(o);
        }

        public string SerializeEncode(object o, string key = "")
        {
            return this.serialize.SerializeEncode(o, key);
        }

        public void SerializeFile(string o, string fileName)
        {
            this.serialize.SerializeFile(o, fileName);
        }
    }
}

